// pages/shop/shop.js
import {
  get_open_id,
  user_login
} from "../../utils/api.js";
var page = 1;
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    unread_num: 0,
    TaskShow: 0,
    openid: '',
    code: '',
    currentCity: "",
    currentCode: 0,
    inputShowed: false,
    inputVal: "",
    indicatorDots: false,
    currentSwiper: 0,
    currentSwiper1: 0,
    currentSwiper2: 0,
    currentSwiper3: 0,
    autoplay: true,
    autoplay1: false,
    interval: 3000,
    duration: 500,
    circular: true,
    imgUrls: [

      {
        img: 'https://cdnimg.51jlkj.com/mingpian/20190713/963f2de8113e97b20c05bc83c27686d258539bc2.png'
      }
    ],
    sellerList: [],
    sellerList1: [],
    more_status: false,

    area_human: 0,
    grids: [

    ],
    huo1_src: [],
    countdown: '',
    endDate2: '2019-05-15',
    left_img: "",
    right_tu: [],
    jrshu: '',
    scollTop: 0,
  },
  // 轮播指示点
  swiperChange: function(e) {
    this.setData({
      currentSwiper1: e.detail.current,
    })
  },
  //解决swiper卡死
  swiperchange: function(e) {
    this.setData({
      currentSwiper: e.detail.current,
    })
  },
  // 轮播指示点
  swiperChange2: function(e) {
    this.setData({
      currentSwiper3: e.detail.current,
    })
  },
  //解决swiper卡死
  swiperchange2: function(e) {
    this.setData({
      currentSwiper2: e.detail.current,
    })
  },
  bindnewList() {
    wx.navigateTo({
      url: '../../pages/contactList/contactList',
    })
  },
  binddw() {
    wx.navigateTo({
      url: '../../shopPages/cityList/cityList',
    })
  },
  // 计时器
  countTime() {
    var that = this;
    var date = new Date();
    var now = date.getTime();
    var endDate = new Date(that.data.endDate2); //设置截止时间
    var end = endDate.getTime();
    var leftTime = parseInt(end) - parseInt(now); //时间差
    var d, h, m, s, ms;
    if (leftTime >= 0) {
      d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      m = Math.floor(leftTime / 1000 / 60 % 60);
      s = Math.floor(leftTime / 1000 % 60);
      ms = Math.floor(leftTime % 1000);
      ms = ms < 100 ? "0" + ms : ms
      s = s < 10 ? "0" + s : s
      m = m < 10 ? "0" + m : m
      h = h < 10 ? "0" + h : h
      that.setData({
        countdown: h + "：" + m + "：" + s,
      })
      //递归每秒调用countTime方法，显示动态时间效果
      setTimeout(that.countTime, 1000);
    } else {
      console.log('已截止')
      that.setData({
        countdown: '00:00:00'
      })
    }

  },
  bindQidai: function() {
    wx.showToast({
      title: '敬请期待',
      icon: 'success',
      duration: 1000
    })
  },
  to_promotion: function() {
    wx.navigateTo({
      url: '../../shopPages/activeShoplist/activeShoplist?state=1'
    })
  },
  to_limited: function() {
    wx.navigateTo({
      url: '../../shopPages/activeShoplist/activeShoplist?state=2&limited=1'
    })
  },
  to_fullR: function(e) {
    if (!e.currentTarget.dataset.idx) {
      wx.navigateTo({
        url: '../../shopPages/spellActivity/spellActivity'
      })
    } else {
      wx.navigateTo({
        url: '../../shopPages/activeShoplist/activeShoplist?state=3'
      })
    }

  },
  to_act_goods: function(e) {
    wx.navigateTo({
      url: '../../shopPages/activeShoplist/activeShoplist?state=5&act_type=' + e.currentTarget.dataset.act_type,
    })
  },
  to_zone: function() {
    wx.navigateTo({
      url: '../../shopPages/activeShoplist/activeShoplist?state=4'
    })
  },
  navss: function() {
    wx.navigateTo({
      url: '../../shopPages/searchMaster/search'
    })
  },
  postBimg: function(e) {
    var that = this
    var url2 = "/mall/mallIndex"
    var params2 = {

    };
    app.HttpPostSend(url2, params2, function(res) {
      if (res.msg !== "success") {
        app.showTipMsg(res.msg);
      } else {
        console.log(res.cat_list)
        that.setData({
          grids: res.cat_list
        })
      }
    });
  },
  // clearTimeout(){
  //   clearTimeout(this.countTime())
  // },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    wx.getSystemInfo({
      success: res => {
        //导航高度
        that.setData({
          statusBarHeight: res.statusBarHeight + 44
        })
      },
      fail(err) {
        console.log(err);
      }
    })
    page = 1;
    // that.clearTimeout()
    that.postBimg()
    that.checkUserInfo()
  },

  // 检测是否需要登录
  checkUserInfo: function() {
    const that = this
    let openid = wx.getStorageSync('openid')
    if (openid) {
      app.globalData.openid = openid
      that.setData({
        openid,
      })
      let url = '/user_api/getInfoByOpenID';
      app.HttpPostSend(
        url, {
          openid: openid,
        },
        function(result_data) {
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            if (!!result_data.data) { //如果后台有数据
              app.globalData.userInfo = {
                ...result_data.data
              }
              wx.setStorage({
                key: 'userInfo',
                data: JSON.stringify({
                  ...result_data.data
                })
              })
              that.setData({
                haveTap: 1,
                userInfo: result_data.data,
                u_id: app.globalData.userInfo.id
              })
              // that.getCarteInfo(app.globalData.userInfo.id)
              that.location_data(app.globalData.userInfo.id);
              app.update_cart(app.globalData.userInfo.id);
              console.log(111111111111111);
              if (that.data.issharecome == true) {
                console.log(123456789);
                that.setData({
                  TaskShow: 3
                })
              }
              try {
                // ai添加纪录 对我感兴趣
                app.aiAddRecord(1)
              } catch (error) {
                console.log(error)
              }
            } else { //如果后台无数据
              wx.login({
                success(res) {
                  let params = {
                    code: res.code
                  }
                  app.HttpGetSend(get_open_id, params, function(result) {
                    if (result.msg != "success") {
                      app.showTipMsg(result.msg);
                    } else {
                      app.globalData.openid = result.data.openid.openid;
                      // app.update_cart(result.data.userinfo.id);
                      that.location_data(result.data.userinfo.id);
                      wx.setStorage({
                        key: 'openid',
                        data: result.data.openid.openid
                      })
                      that.setData({
                        openid: result.data.openid.openid
                      })
                      that.setData({
                        // TaskShow: 1,
                        openid: result.data.openid.openid
                      })
                    }
                  })
                }
              })
            }
          }
        })
    } else {
      wx.login({
        success(res) {
          let params = {
            code: res.code
          }
          app.HttpGetSend(get_open_id, params, function(result) {
            if (result.msg != "success") {
              app.showTipMsg(result.msg);
            } else {
              app.globalData.openid = result.data.openid.openid;
              // app.update_cart(result.data.userinfo.id);
              that.location_data(result.data.userinfo.id);
              wx.setStorage({
                key: 'openid',
                data: result.data.openid.openid
              })
              that.setData({
                openid: result.data.openid.openid
              })
              that.setData({
                // TaskShow: 1,
                openid: result.data.openid.openid
              })
            }
          })
        }
      })
    }
    let systemInfo = wx.getSystemInfoSync()
    app.globalData.systemInfo = systemInfo
    this.setData({
      systemInfo
    })
  },

  toGoodsDetail: function(e) {
    wx.navigateTo({
      url: e.currentTarget.dataset.url,
    })
  },

  // 获取用户信息
  bindGetUserInfo: function(e) {
    const that = this
    let userInfo = e.detail.userInfo
    app.globalData.authSettingUser = 1;
    try {
      app.HttpPostSend(
        user_login, {
          openid: that.data.openid,
          username: userInfo.nickName,
          // phone: that.data.phone,
          // code: that.data.code,
          logo: userInfo.avatarUrl,
          sex: userInfo.gender
        },
        function(result_data) {
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            let userInfo = {
              ...result_data.data
            }
            app.globalData.userInfo = userInfo
            wx.setStorage({
              key: 'userInfo',
              data: JSON.stringify(userInfo)
            })
            that.setData({
              TaskShow: 0,
              haveTap: 1,
              userInfo: userInfo
            })
            // that.getCarteInfo(userInfo.id)
            if (that.data.issharecome == true) {
              that.setData({
                TaskShow: 3
              })
            }
            try {
              // ai添加纪录 对我感兴趣
              app.aiAddRecord(1)
            } catch (error) {
              console.log(error)
            }
          }
        })
    } catch (error) {

    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    var day3 = new Date();
    day3.setTime(day3.getTime() + 24 * 60 * 60 * 1000);
    var s3 = day3.getFullYear() + "/" + (day3.getMonth() + 1) + "/" + day3.getDate();
    that.setData({
      endDate2: s3
    });
    that.countTime()

    // that.setData({

    //   sellerList: [],
    //   page:1
    // });
    // 检查当前城市
    // const currentCity = wx.getStorageSync('currentCity');
    // if (currentCity && currentCity !== this.data.currentCity) {
    //   this.setData({ currentCity });
    // }
    // this.setData({
    //   currentCity:app.globalData.currentCity,
    //   currentCode: app.globalData.currentCode,
    // });

    // this.getLocation();
    that.message();
  },
  message: function() {
    var that = this;
    var url = '/chat_api/getUnReadNum';
    var params = {
      uid: app.globalData.userInfo.id,
      currentCode: app.globalData.currentCode,
    };

    app.HttpPostSend(url, params, function(res) {
      that.setData({
        unread_num: res.data[0],
        area_human: res.data[1],
      });
    })
  },
  location_data: function(uid) {
    var that = this;
    if (!app.globalData.currentCode) {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) { //非初始化进入该页面,且未授权
            wx.showModal({
              title: '是否授权当前位置',
              content: '需要获取您的地理位置，请确认授权，否则无法获取您所需数据',
              showCancel: false,
              success: function(res) {
                if (res.cancel) {

                  wx.showToast({
                    title: '授权失败',
                    icon: 'success',
                    duration: 1000
                  })
                } else if (res.confirm) {
                  wx.openSetting({
                    success: function(dataAu) {
                      if (dataAu.authSetting["scope.userLocation"] == true) {
                        wx.showToast({
                          title: '授权成功',
                          icon: 'success',
                          duration: 1000
                        })
                        //再次授权，调用getLocationt的API
                        that.getLocation(uid);
                      } else {
                        wx.showToast({
                          title: '授权失败',
                          icon: 'success',
                          duration: 1000
                        })
                      }
                    }
                  })
                }
              }
            })
          } else if (res.authSetting['scope.userLocation'] == undefined) { //初始化进入

            that.getLocation(uid);
          } else { //授权后默认加载

            that.getLocation(uid);
          }
        }
      })
    } else {
      that.setData({
        currentCityCode: app.globalData.currentCode,
        currentCity: app.globalData.currentCity
      })
      that.getMallSeller(app.globalData.latitude, app.globalData.longitude, app.globalData.currentCode);
    }
  },

  getLocation: function(uid) {

    const that = this;
    wx.showLoading({
      title: '定位中',
    })
    wx.getLocation({
      type: 'gcj02',
      success: function(res) {

        // console.log("测试：" + res);
        let latitude = res.latitude
        let longitude = res.longitude
        app.globalData.latitude = res.latitude;
        app.globalData.longitude = res.longitude;
        let keys = "PCZBZ-6Y3W6-HVVSM-E22YX-JTSYO-QJBZD"
        app.HttpPostSend('/mall/get_location', {
          latitude: latitude,
          longitude: longitude,
          uid: uid
        }, function(res) {
          wx.hideLoading();
          var re_data = res;
          if (re_data.code > 0) {
            that.setData({
              currentCityCode: re_data.adcode,
              currentCity: re_data.district,
              area_human: re_data.area_human,
              indicatorDots: false,
              currentSwiper: 0,
              currentSwiper1: 0,
              autoplay: true,
              autoplay1: false,
              interval: 3000,
              duration: 500,
              circular: true,
            })
            app.globalData.currentCity = re_data.district;
            app.globalData.currentCode = re_data.adcode;

            that.getMallSeller(app.globalData.latitude, app.globalData.longitude, re_data.adcode);
          } else {
            wx.showModal({
              title: '提示',
              content: '获取定位失败，请手动选择地区',
              showCancel: false,
              success: function(res) {
                if (res.cancel) {

                  wx.showToast({
                    title: '失败',
                    icon: 'success',
                    duration: 1000
                  })
                } else if (res.confirm) {
                  wx.navigateTo({
                    url: '../../shopPages/cityList/cityList',
                  })
                  return false;
                }
              }
            })
          }

        });

      },
      fail: res => {
        wx.hideLoading();
        console.log('授权失败');
        wx.showModal({
          title: '是否授权当前位置',
          content: '需要获取您的地理位置，请确认授权，否则无法获取您所需数据',
          showCancel: false,
          success: function(res) {
            wx.hideLoading();
            if (res.cancel) {

              wx.showToast({
                title: '授权失败',
                icon: 'success',
                duration: 1000
              })
            } else if (res.confirm) {
              wx.openSetting({
                success: function(dataAu) {
                  if (dataAu.authSetting["scope.userLocation"] == true) {
                    wx.showToast({
                      title: '授权成功',
                      icon: 'success',
                      duration: 1000
                    })
                    //再次授权，调用getLocationt的API
                    that.getLocation();
                  } else {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'success',
                      duration: 1000
                    })
                  }
                }
              })
            }
          }
        })
      }
    })
  },

  /*
   * 根据位置获取商城数据
   */
  getMallSeller: function(latitude, longitude, area_code, ini_page) {

    var that = this
    if (ini_page > 0) {
      page = 1;
    }
    var url2 = "/mall/mallSeller"
    var params2 = {
      latitude: latitude,
      longitude: longitude,
      area_code: area_code,
      pageno: page,
      area_human: that.data.area_human,
      share_id: app.globalData.shareOptions.share_id
    };
    var more_status = that.data.more_status;
    var new_list = that.data.sellerList;
    app.HttpPostSend(url2, params2, function(res) {
      if (res.msg !== "success") {
        app.showTipMsg(res.msg);
      } else {
        page = parseInt(page) + 1;
        if (page == 2) {
          // console.log(res.banner_list);
          that.setData({
            indicatorDots: false,
            currentSwiper: 0,
            currentSwiper1: 0,
            autoplay: true,
            autoplay1: false,
            interval: 3000,
            duration: 500,
            circular: true,
            imgUrls: res.banner_list,
            huo1_src: res.act_promotion.img,
            right_tu: res.full_reduction.img,
            act_discount_zone: res.act_discount_zone.img,
            left_img: res.act_limited.img,
            // cost: res.act_imgs != undefined ? res.act_imgs[0] : [],
            // Rush: res.act_imgs != undefined ? res.act_imgs[1] : []
          })


          new_list = [];
        } else {
          // console.log(2222);
        }
        if (res.seller.length < 4) {
          more_status = false;
        } else {
          more_status = true;
        }
        var list = res.seller;
        for (let i = 0; i < list.length; i++) {
          new_list.push(list[i]);
          if (list[i].label != null) {
            const label = list[i].label.split(',')
            list[i].label = label
          }

        }

        // if (res.area_human != undefined && res.area_human > 0) {
        //   that.setData({
        //     area_human: res.area_human,
        //   });
        // }

        that.setData({
          sellerList: new_list,
          seller_discount_zone: res.seller_discount_zone,
          more_status: more_status,

        });


      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this;
    // console.log(that.data.more_status);
    if (that.data.more_status == true) {
      var that = this;
      // 显示加载图标

      // 页数+1
      that.getMallSeller(app.globalData.latitude, app.globalData.longitude, app.globalData.currentCode);

    } else {
      wx.hideLoading();
    }
  },

  getSellerList: function() {

  },

  toMyMall: function(e) {
    app.globalData.SwitchTabParams.v_id = e.currentTarget.dataset.uid;

    if (e.currentTarget.dataset.food_mall > 0) {
      wx.navigateTo({
        url: '/shopPages/shopxq/shopxq',
      })
    } else {
      wx.navigateTo({
        // url: '../../pages/myMall/myMall',
        url: '/shopPages/personalShop/personalShop'
      })
    }

  },
  // .监听页面滚动距离scrollTop
  onPageScroll: function(e) {
    this.setData({
      scollTop: e.scrollTop
    })
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function() {

  // },
  // 视图滚动到底部时触发   点击顶部状态栏会返回顶部
  onScrollLower() {

    let {
      page,
      rows,
      guessLike,
      isLoading,
      isLoadingAll
    } = this.data;

    if (isLoading || isLoadingAll) return;

    this.setData({
      isLoading: true
    });

    req.getShops({}, {
      page: ++page,
      rows,
    }).then((res) => {
      if (res.code === 200 && res.msg.length !== 0) {
        this.setData({
          guessLike: [...guessLike, ...res.msg],
          page: page,
          isLoading: false
        })
      } else {
        this.setData({
          isLoading: false,
          isLoadingAll: true
        })
      }
    }).catch((err) => {
      console.error(err);
    });
  }
})